#include "TCP.h"
#include <sys/types.h>
#include <sys/wait.h>

void child_run(int cfd)
{
    set_noblock(cfd);
    char msg[1024];
    while(1)
    {
        memset(msg,0,1024);
        read_noblock(cfd,msg,sizeof(msg));
        if(strlen(msg)>0)
        {
            if(strcmp(msg,"quit\n")==0)
            {
                exit(0);
            }
            
        }
        send(cfd,msg,strlen(msg),MSG_NOSIGNAL);
    }
   
}
void wait_child(int sig)
{
    waitpid(-1,NULL,0);
    printf("child is exit\n");
}
int main(int argc,char **argv)
{   
    int sockfd;
    int cfd;
    pid_t pid;
    struct sockaddr_in c_addr;
    socklen_t c_size;
    signal(SIGCHLD,wait_child);
    sockfd=TCP_server_create();
    while(1)
    {
        c_size=sizeof(struct sockaddr_in);
        cfd=accept(sockfd,(struct sockaddr*)&c_addr,&c_size);
        if(cfd<0)
        {
           if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
           { 
                perror("accpet error\n");
                exit(1);
            }
        }
        if(cfd > 0)
        {
        pid=fork();
        if(pid < 0)
        {
            perror("fork error\n");
            exit(1);
        }

        if(pid == 0)
        {
           child_run(cfd);
        }
        else if(pid> 0)
        {
            close(cfd);
        }
        }
    }

    return 0;
}